package com.southern.gateway.filter;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.server.ServerWebExchange;

import com.southern.gateway.base.ResultModel;
import com.southern.gateway.feign.sysApi.SysApiLogin;
import com.southern.gateway.service.PermissionServiceImpl;
import com.southern.gateway.util.IpUtils;

import reactor.core.publisher.Mono;

public class PermissionCheckFilter extends AbstractGatewayFilterFactory<PermissionCheckFilter.Config> {

	private static final Logger logger = LoggerFactory.getLogger(PermissionCheckFilter.class);

    @Autowired
    private SysApiLogin sysApiLogin;
    
    @Autowired
    private PermissionServiceImpl permissionService;
    
	@Value("${gateway.loginUrl}")
	private String LOGIN_URL;

	public PermissionCheckFilter() {
		super(Config.class);
	}

	@Override
	public GatewayFilter apply(Config config) {
		return (exchange, chain) -> {
			String ip = IpUtils.getIpAddress(exchange.getRequest());
			String uriPath = exchange.getRequest().getURI().getPath();
			ServerHttpRequest request = exchange.getRequest().mutate().header("X-Forwarded-For", ip).build();
			ServerHttpResponse response= exchange.getResponse();
			String headertoken = request.getHeaders().getFirst("Authorization");
			logger.info("获取token值："+headertoken);
			// 如果走公共url，不要校验是否登录和跳转
			PathMatcher matcher = new AntPathMatcher();
			if (permissionService.getPublicUrls().stream().anyMatch(x -> matcher.match(x, uriPath))) {
				logger.info("公共url放过");
				return chain.filter(exchange);
			}
			//前端的Authorization不为空的情况下
			if(headertoken!=null) {
				//判断是否带有前辍Bearer
				if (headertoken.contains("Bearer")){
					//替换掉前辍Bearer
					headertoken = headertoken.replace("Bearer", "").trim();
					//查询token是否过期
					ResultModel userinfo=sysApiLogin.checkTokenIsEffect(headertoken);
					if(userinfo!=null) {
						//查询到用户状态码为0，表示没有过期
						if("0".equals(userinfo.getCode())){
							//将token带给下游
							ServerHttpRequest req = exchange.getRequest().mutate().header("X-API-TOKEN", headertoken).build();
							exchange = exchange.mutate().request(req).build();
						}else {
							logger.info(" 非ajax直接跳转至登录页面");
							response.setStatusCode(HttpStatus.SEE_OTHER);
							logger.info("LOGIN_URL" + LOGIN_URL);
							response.getHeaders().set("Location", LOGIN_URL);

							return exchange.getResponse().setComplete();
						}
					}else {
						logger.info(" 非ajax直接跳转至登录页面");
						response.setStatusCode(HttpStatus.SEE_OTHER);
						logger.info("LOGIN_URL" + LOGIN_URL);
						response.getHeaders().set("Location", LOGIN_URL);

						return exchange.getResponse().setComplete();
					}
			    }
			}else {
				logger.info(" 非ajax直接跳转至登录页面");
				response.setStatusCode(HttpStatus.SEE_OTHER);
				logger.info("LOGIN_URL" + LOGIN_URL);
				response.getHeaders().set("Location", LOGIN_URL);

				return exchange.getResponse().setComplete();
			}
			
			return chain.filter(exchange);
		};
	} // end apply function

	public static class Config {
		// Put the configuration properties for your filter here
	}
	private   Mono<Void> fallbackToLogin(ServerWebExchange exchange) {
		//返回登录页面
		ServerHttpResponse response= exchange.getResponse();
		logger.info(" 非ajax直接跳转至登录页面");
		response.setStatusCode(HttpStatus.SEE_OTHER);
		logger.info("LOGIN_URL" + LOGIN_URL);
		response.getHeaders().set("Location", LOGIN_URL);

		return exchange.getResponse().setComplete();
	}
	private Boolean isAjaxRequest(ServerHttpRequest req) {
		// 判断是否为ajax请求，默认不是
		boolean isAjaxRequest = false;
		List<String> XMLHttpRequest = req.getHeaders().get("x-requested-with");
		if (null != XMLHttpRequest && XMLHttpRequest.size() > 0) {
			for (String headerValue : XMLHttpRequest) {
				if (headerValue.equals("XMLHttpRequest")) {
					isAjaxRequest = true;
					break;
				}
			}
		}
		return isAjaxRequest;
	}

	

}
